package p.ithorns.framework.web.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.web.context.request.async.TimeoutCallableProcessingInterceptor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import p.ithorns.framework.common.thread.ThreadPoolFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * MvcConfig
 * 自动配置feign扫描包 使用方零配置 微服务本身不加载自己的API中的feign
 * //@ConditionalOnExpression("#{!environment['spring.application.name'].endsWith('" + ProviderApiAutoConfig.SERVICE_NAME + "')}")
 * //@EnableFeignClients(basePackages = "com.hcc.ws.api")
 *
 * @author Created By Ht_L. 2018/11/1-15:50
 */
@Configuration
public class DefaultWebMvcConfig extends WebMvcConfigurationSupport {

    @Value("${server.port}")
    private int httpPort;

    @Bean
    public TimeoutCallableProcessingInterceptor timeoutInterceptor() {
        return new TimeoutCallableProcessingInterceptor();
    }

    /**
     * 设置超时 (application.properties中设置spring.mvc.async.request-timeout=15000也可以)
     */
    @Override
    public void configureAsyncSupport(final AsyncSupportConfigurer configurer) {
        //设置线程池来处理异步请求
        ExecutorService executorService = ThreadPoolFactory.create(4, 8,"web");
        configurer.setTaskExecutor(new ConcurrentTaskExecutor(executorService));
        configurer.setDefaultTimeout(30000);
        configurer.registerCallableInterceptors(timeoutInterceptor());
    }


    /**
     * 静态资源拦截器配置
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");

        registry.addResourceHandler("/doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }


    @Bean
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        //设置日期格式
        //ObjectMapper objectMapper = new ObjectMapper();
        //SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:DD:ss");
        //objectMapper.setDateFormat(smt);
        //mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);

        //设置中文编码格式
        List<MediaType> list = new ArrayList<>();
        list.add(MediaType.APPLICATION_JSON_UTF8);
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
        return mappingJackson2HttpMessageConverter;
    }

    /**
     * 跨域配置
     */
//    @Value("${server.cors.origins}")
//    private String accessControlAllowOrigin;

    /**
     * 跨域 最好设计具体的地址，防止第三方恶意访问  // 统一在网关处理
     */
//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**")
//                .allowedOrigins(StringUtil.trimAllWhitespace(accessControlAllowOrigin).split(","))
//                .allowedMethods("GET", "POST", "OPTIONS", "PUT", "DELETE")
//                .allowCredentials(true).maxAge(3600);
//    }


//    @Bean
//    public ServletWebServerFactory servletContainer() {
//        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
//        tomcat.addAdditionalTomcatConnectors(createStandardConnector());
//        return tomcat;
//    }
//
//    private Connector createStandardConnector() {
//        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
//        connector.setPort(httpPort);
//        return connector;
//    }

}